﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using AutoResumeSend.Entity;
using AutoResumeSend.DAC;
using System.Net.Mail;
using System.Net.Mime;
using System.IO;
namespace AutoResumeSend.Componments
{
    public class ResumeSendManager
    {
        HttpDirectVisitor httpThead = new HttpDirectVisitor();
        public void CatchJob()
        {
            //配置要抓取的站点
            WebSiteList web = new WebSiteList();
            List<WebSiteInfo> list = web.list;
            //申明抓取职位结果的容器
            List<WebSiteInfo> resultList = new List<WebSiteInfo>();
            //申明抓取的页面html
            string c_html = string.Empty;
            //职位要求年限
            int jobYear = 0;
            //工作地区
            string jobArea = string.Empty;
            //职位名称
            string jobName = string.Empty;
            //职位发布时间
            DateTime dtPublish = DateTime.MinValue;
            //职位详情链接地址
            string jobUrl = string.Empty;
            //职位标题是否包含指定关键字
            bool isReg = false;
            string emailReg = @"\w+\@\w+\.[a-z]{2,3}";

            string publishTime = string.Empty;
            int year = DateTime.Now.Year; ;
            int month = DateTime.Now.Month; ;
            int day = DateTime.Now.Day;
            int h = DateTime.Now.Hour;
            int m = DateTime.Now.Minute;
            int s = DateTime.Now.Second;

            try
            {
                for (int page = 1; page < Config.PageCount; page++)
                {
                    for (int index = 0; index < list.Count; index++)
                    {
                        c_html = httpThead.ReadUrl(string.Format( list[index].WebLink,page), list[index].Encoding);

                        if (string.IsNullOrEmpty(c_html))
                            continue;

                        MatchCollection ma = Regex.Matches(c_html, list[index].RegMenuString, RegexOptions.IgnoreCase);

                        foreach (Match mc in ma)
                        {
                            if (mc.Groups.Count > list[index].RegOccurMenuGroupMax)
                            {
                                if (!int.TryParse(mc.Groups[list[index].RegJobYearIndex].Value.ToString(), out jobYear))
                                    jobYear = 0;

                                //工作年限不符合 就不要往下匹配
                                if (jobYear == 0 || jobYear > Config.MaxJobYear)
                                    continue;

                                jobArea = mc.Groups[list[index].RegJobProvinceIndex].Value.ToString();
                                //工作地区不符合就不要往下匹配
                                if (Config.JobArea.IndexOf(jobArea) < 0)
                                    continue;
                                jobName = mc.Groups[list[index].RegOccurTitleIndex].Value.ToString();

                                //职位标题不包含指定的关键字就不要再往下匹配  
                                string[] jobTitleKey = Config.JobTitle.Split(',');
                                if (jobTitleKey != null && jobTitleKey.Length > 0)
                                {
                                    for (int keyIndex = 0; keyIndex < jobTitleKey.Length; keyIndex++)
                                    {
                                        if (jobName.ToLower().Contains(jobTitleKey[index].ToLower()))
                                        {
                                            isReg = true;
                                            break;
                                        }
                                    }
                                }
                                if (!isReg)
                                    continue;

                                isReg = false;

                                publishTime = mc.Groups[list[index].RegPublishTimeIndex].Value.ToString();
                                if (!string.IsNullOrEmpty(publishTime))
                                {
                                    MatchCollection maTime = Regex.Matches(publishTime, @"\d{1,4}", RegexOptions.IgnoreCase);

                                    if (maTime.Count == 2) //月日格式
                                    {
                                        if (!int.TryParse(maTime[0].Groups[0].Value.ToString(), out month))
                                            month = DateTime.Now.Month;

                                        if (!int.TryParse(maTime[1].Groups[0].Value.ToString(), out day))
                                            day = DateTime.Now.Day;
                                    }
                                    else if (maTime.Count == 3) //年月日格式
                                    {
                                        if (!int.TryParse(maTime[1].Groups[0].Value.ToString(), out month))
                                            month = DateTime.Now.Month;

                                        if (!int.TryParse(maTime[2].Groups[0].Value.ToString(), out day))
                                            day = DateTime.Now.Day;

                                    }
                                    else if (maTime.Count == 5) //年月日时分格式
                                    {
                                        if (!int.TryParse(maTime[1].Groups[0].Value.ToString(), out month))
                                            month = DateTime.Now.Month;

                                        if (!int.TryParse(maTime[2].Groups[0].Value.ToString(), out day))
                                            day = DateTime.Now.Day;

                                        if (!int.TryParse(maTime[3].Groups[0].Value.ToString(), out h))
                                            h = DateTime.Now.Hour;
                                        if (!int.TryParse(maTime[4].Groups[0].Value.ToString(), out m))
                                            m = DateTime.Now.Hour;
                                    }
                                    else if (maTime.Count == 6) //年月日时分秒格式
                                    {
                                        if (!int.TryParse(maTime[1].Groups[0].Value.ToString(), out month))
                                            month = DateTime.Now.Month;

                                        if (!int.TryParse(maTime[2].Groups[0].Value.ToString(), out day))
                                            day = DateTime.Now.Day;

                                        if (!int.TryParse(maTime[3].Groups[0].Value.ToString(), out h))
                                            h = DateTime.Now.Hour;

                                        if (!int.TryParse(maTime[4].Groups[0].Value.ToString(), out m))
                                            m = DateTime.Now.Hour;
                                        if (!int.TryParse(maTime[5].Groups[0].Value.ToString(), out s))
                                            s = DateTime.Now.Hour;
                                    }
                                }
                                dtPublish= new DateTime(year, month, day, h, m, s);


                                //如果抓取到得时间和最近一次抓取的时间间隔和大于配置的时间间隔就不要再往下抓取
                                if (dtPublish == DateTime.MinValue || DateTime.Now.Subtract(dtPublish).Days > Config.IntervalDay)
                                    continue;
                                jobUrl = mc.Groups[list[index].RegOccurUrlIndex].Value.ToString();

                                WebSiteInfo catchedWeb = new WebSiteInfo();
                                catchedWeb.WebId = list[index].WebId;
                                catchedWeb.WebName = list[index].WebName;
                                if (!jobUrl.ToLower().Contains("http://"))
                                {
                                    jobUrl = list[index].Host + jobUrl;
                                }
                                catchedWeb.WebLink = jobUrl;
                                catchedWeb.JobArea = jobArea;
                                catchedWeb.JobYear = jobYear;
                                catchedWeb.OccurTitle = jobName;
                                catchedWeb.PublishTime = dtPublish;
                                //抓取职位详情页面内容
                                c_html = httpThead.ReadUrl(jobUrl, list[index].Encoding);
                                Match maEmail = Regex.Match(c_html, emailReg, RegexOptions.IgnoreCase);
                                if (maEmail != null)
                                {
                                    catchedWeb.CompanyEmail = maEmail.Groups[0].Value.ToString();
                                }
                               

                                //发送邮件
                                MailInfo mail = new MailInfo();
                                mail.Subject = Config.SubjectTitle + jobName;

                                mail.From = Config.Mail;
                                mail.To = catchedWeb.CompanyEmail;
                                mail.FromDisplayName = "涂云横";
                                string attchmentsPath = Config.AttchmentsPath;
                                if (string.IsNullOrEmpty(attchmentsPath))
                                {
                                    attchmentsPath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "resume.doc");
                                }
                                mail._attachmentPath = attchmentsPath;
                                string bodyPath = Config.EmailBodyPath;
                                if (string.IsNullOrEmpty(bodyPath))
                                {
                                    bodyPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "resume.txt");
                                }
                                string body = File.ReadAllText(bodyPath);
                                mail.Body = body;
                                SendMailManager mailMgr = new SendMailManager();
                                mailMgr.sendMail(mail, Config.EmailServrceUrl, Config.EmailPort, Config.LoginName, Config.Password);

                                //添加数据库
                                SqlManager sqlMgr = new SqlManager();
                                sqlMgr.AddResumeSendInfo(catchedWeb);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError(ex.ToString());
                ex = null;
            }
        }

       
    }
}
